package com.fancy.learncenter.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.service.carrier.CarrierMessagingService;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.bean.AppDataBean;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.common.DownLoadUtil;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.common.StatusBarCompat;
import com.fancy.learncenter.fragment.HomeFragment;
import com.fancy.learncenter.fragment.MsgFragment;
import com.fancy.learncenter.fragment.MyselfFragment;
import com.fancy.learncenter.fragment.ToothFragment;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.PopupWindowRealease;
import com.superservice.lya.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import me.leolin.shortcutbadger.ShortcutBadger;

public class MainActivity extends BaseActivity {

    public static int MAIN_REQUEST_CODE = 10009;

    @Bind(R.id.framelayout_contain)
    FrameLayout framelayoutContain;
    @Bind(R.id.home_icon)
    ImageView homeIcon;
    @Bind(R.id.home_font)
    TextView homeFont;
    @Bind(R.id.friend_icon)
    ImageView friendIcon;
    @Bind(R.id.friend_font)
    TextView friendFont;
    @Bind(R.id.fancy_icon)
    ImageView fancyIcon;
    @Bind(R.id.fancy_font)
    TextView fancyFont;
    @Bind(R.id.my_icon)
    ImageView myIcon;
    @Bind(R.id.my_font)
    TextView myFont;
    @Bind(R.id.unread_num)
    public TextView unreadNum;

    private HomeFragment homeFragment;
    private ToothFragment toothFragment;
    private MsgFragment msgFragment;
    private MyselfFragment myselfFragment;
    private Fragment tempFrag;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main, getResources().getColor(R.color.toolbar_color));
        ButterKnife.bind(this);
        showIndex(1);

        updata();

        if (!TextUtils.isEmpty(SPUtils.getToken())) {
            Utils.savePosition();
        }

        RongIM.getInstance().addUnReadMessageCountChangedObserver(new IUnReadMessageObserver() {
            @Override
            public void onCountChanged(int i) {

                if (i == 0) {
                    unreadNum.setText("0");
                    unreadNum.setVisibility(View.GONE);
                } else if (i > 99) {
                    unreadNum.setText("99+");
                    unreadNum.setVisibility(View.VISIBLE);
                } else {
                    unreadNum.setText(i + "");
                    unreadNum.setVisibility(View.VISIBLE);
                }

                if (msgFragment != null) {
//                    msgFragment.notifyRead(i);
                }
                if (Build.MANUFACTURER.equalsIgnoreCase("vivo")) {

                    vivoShortCut(MainActivity.this, i + "");

                }
                if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {

                    xiaomiShortCut(i);

                } else {

                    ShortcutBadger.applyCount(MainActivity.this, i); //for 1.1.4+
                }


            }
        }, Conversation.ConversationType.PRIVATE);

    }

    private void showIndex(int index) {

        if (MyApplication.ryIsLogin) {
            Utils.loginRongYun();
        }

        changeUi(index);
        switch (index) {
            case 1:
                transaction = getSupportFragmentManager().beginTransaction();
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.framelayout_contain, homeFragment);
                }

                if (tempFrag == homeFragment) {
                    return;
                } else if (tempFrag != null) {
                    transaction.hide(tempFrag);
                } else {
                    tempFrag = homeFragment;
                }
                if (myselfFragment != null) {
                    transaction.hide(myselfFragment);
                } else if (msgFragment != null) {
                    transaction.hide(msgFragment);
                } else if (homeFragment != null) {
                    transaction.hide(homeFragment);
                } else if (toothFragment != null) {
                    transaction.hide(toothFragment);
                }

                transaction.show(homeFragment);
                transaction.commit();
                tempFrag = homeFragment;
                break;
            case 2:
                transaction = getSupportFragmentManager().beginTransaction();
                if (toothFragment == null) {
                    toothFragment = new ToothFragment();
                    transaction.add(R.id.framelayout_contain, toothFragment);
                }

                if (tempFrag == toothFragment) {
                    return;
                } else if (tempFrag != null) {
                    transaction.hide(tempFrag);
                }
                if (myselfFragment != null) {
                    transaction.hide(myselfFragment);
                } else if (msgFragment != null) {
                    transaction.hide(msgFragment);
                } else if (homeFragment != null) {
                    transaction.hide(homeFragment);
                } else if (toothFragment != null) {
                    transaction.hide(toothFragment);
                }

                transaction.show(toothFragment);
                transaction.commit();
                tempFrag = toothFragment;
                break;
            case 3:

                break;
            case 4:
                transaction = getSupportFragmentManager().beginTransaction();
                if (msgFragment == null) {
                    msgFragment = new MsgFragment();
                    transaction.add(R.id.framelayout_contain, msgFragment);
                }
                if (tempFrag == msgFragment) {
                    return;
                } else if (tempFrag != null) {
                    transaction.hide(tempFrag);
                }


                if (myselfFragment != null) {
                    transaction.hide(myselfFragment);
                } else if (msgFragment != null) {
                    transaction.hide(msgFragment);
                } else if (homeFragment != null) {
                    transaction.hide(homeFragment);
                } else if (toothFragment != null) {
                    transaction.hide(toothFragment);
                }

                transaction.show(msgFragment);
                transaction.commit();
                tempFrag = msgFragment;
                break;
            case 5:
                transaction = getSupportFragmentManager().beginTransaction();
                if (myselfFragment == null) {
                    myselfFragment = new MyselfFragment();
                    transaction.add(R.id.framelayout_contain, myselfFragment);
                }
                if (tempFrag == myselfFragment) {
                    return;
                } else if (tempFrag != null) {
                    transaction.hide(tempFrag);
                }
                if (myselfFragment != null) {
                    transaction.hide(myselfFragment);
                } else if (msgFragment != null) {
                    transaction.hide(msgFragment);
                } else if (homeFragment != null) {
                    transaction.hide(homeFragment);
                } else if (toothFragment != null) {
                    transaction.hide(toothFragment);
                }

                transaction.show(myselfFragment);
                transaction.commit();
                tempFrag = myselfFragment;
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.MyLog("onActivityResult", "resultCode====" + resultCode);
    }


    public void updata() {

        Map map = new HashMap();
        map.put("versionName", Utils.getVersionName());
        map.put("agent", "android");

        if ("xiaomi".equals(Utils.getVersionName())) {
            map.put("brand", getDeviceBrand());
        } else if ("huawei".equals(Utils.getVersionName())) {
            map.put("brand", getDeviceBrand());
        } else {
            map.put("brand", "others");
        }

        HttpMehtod.getInstance().upDataApp(map, new IdeaObserver<BaseDataBean<AppDataBean>>() {

            @Override
            public void onSuccess(BaseDataBean<AppDataBean> appDataBeanBaseDataBean) {

                if (appDataBeanBaseDataBean.getData() != null && appDataBeanBaseDataBean.getData().isHave_update_app()) {
                    DownLoadUtil.from(MainActivity.this)
                            .showNotification(true)
                            .serverVersionName(appDataBeanBaseDataBean.getData().getVersion_name()) //服务器versionName
                            .updateInfo(appDataBeanBaseDataBean.getData().getDescription())
                            .isForce(appDataBeanBaseDataBean.getData().isIs_force_update())
                            .apkPath(appDataBeanBaseDataBean.getData().getSite()) //最新apk下载地址
                            .update();
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });


    }

    @OnClick({R.id.home, R.id.friend, R.id.release, R.id.fancy, R.id.my})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home:
                StatusBarCompat.compat(this, getResources().getColor(R.color.toolbar_color));
//                StatusBarCompat.compat(this, Color.parseColor("#fe9011"));

                showIndex(1);

                break;
            case R.id.friend:
                StatusBarCompat.compat(this, getResources().getColor(R.color.toolbar_color));
//                StatusBarCompat.compat(this, getResources().getColor(R.color.toolbar_color));
                showIndex(2);

                break;
            case R.id.release:
//                showIndex(3);#FFEDBE 100%

                if (TextUtils.isEmpty(SPUtils.getToken())) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    show();
                }

//                ToastUtil.show("弹框");
                break;
            case R.id.fancy:

                if (TextUtils.isEmpty(SPUtils.getToken())) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    StatusBarCompat.compat(this, getResources().getColor(R.color.toolbar_color));
                    showIndex(4);
                }

                break;
            case R.id.my:

                if (TextUtils.isEmpty(SPUtils.getToken())) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    StatusBarCompat.compat(this, Color.parseColor("#fda712"));
                    showIndex(5);
                }

                break;
        }
    }

    private void changeUi(int index) {
        homeIcon.setImageResource(R.mipmap.default_home);
        homeFont.setTextColor(getResources().getColor(R.color.black));

        friendIcon.setImageResource(R.mipmap.default_yayi);
        friendFont.setTextColor(getResources().getColor(R.color.black));

        fancyIcon.setImageResource(R.mipmap.default_msg);
        fancyFont.setTextColor(getResources().getColor(R.color.black));


        myIcon.setImageResource(R.mipmap.default_my);
        myFont.setTextColor(getResources().getColor(R.color.black));

        switch (index) {
            case 1:
                homeIcon.setImageResource(R.mipmap.default_home_selected);
                homeFont.setTextColor(getResources().getColor(R.color.orange));
                break;
            case 2:
                friendIcon.setImageResource(R.mipmap.default_yayi_selected);
                friendFont.setTextColor(getResources().getColor(R.color.orange));
                break;
            case 3:
                break;
            case 4:
                fancyIcon.setImageResource(R.mipmap.default_msg_selected);
                fancyFont.setTextColor(getResources().getColor(R.color.orange));
                break;
            case 5:
                myIcon.setImageResource(R.mipmap.default_my_selected);
                myFont.setTextColor(getResources().getColor(R.color.orange));
                break;

        }
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    PopupWindowRealease popupWindowRealease;

    private void show() {

        if (popupWindowRealease == null) {
            popupWindowRealease = new PopupWindowRealease(this, framelayoutContain);
        }

        popupWindowRealease.showPopupWindow();
    }

    long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (popupWindowRealease != null && popupWindowRealease.isShowing()) {
            popupWindowRealease.dismiss();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static void vivoShortCut(Context context, String num) {
        Intent localIntent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
        localIntent.putExtra("packageName", context.getPackageName());
        String launchClassName = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getClassName();
        localIntent.putExtra("className", launchClassName);
//        if (TextUtils.isEmpty(num)) {
//            num = "";
//        } else {
//            int numInt = Integer.valueOf(num);
//            if (numInt > 0) {
//                if (numInt > 99) {
//                    num = "99";
//                }
//            } else {
//                num = "0";
//            }
//        }
        localIntent.putExtra("notificationNum", Integer.parseInt(num));
        context.sendBroadcast(localIntent);
    }

    public void xiaomiShortCut(int num) {
        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification.Builder builder = new Notification.Builder(this)

                .setContentTitle("title").setContentText("text").setSmallIcon(R.drawable.icon);

        Notification notification = builder.build();

        try {

            Field field = notification.getClass().getDeclaredField("extraNotification");

            Object extraNotification = field.get(notification);

            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);

            method.invoke(extraNotification, num);

        } catch (Exception e) {

            e.printStackTrace();

        }

        mNotificationManager.notify(0, notification);
    }
}
